package com.zmx.user.web;

import com.zmx.common.common.utils.HttpUtil;
import com.zmx.common.common.utils.VerifyCodeUtil;
import com.zmx.common.common.web.rest.ResponseResult;
import com.zmx.user.config.WxConfig;
import com.zmx.user.dto.WxUserInfo;
import com.zmx.user.service.LoginService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;


/**
 * @Description: 用户登录控制器
 * @ClassName: LoginController
 * @Author zhaomxr
 * @Date 2021-11-09 11:19
 */
@Slf4j
@RestController
public class LoginController {

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private LoginService loginService;

    @ApiOperation(value = "微信授权登录", tags = "微信授权登录")
    @PostMapping("/login/wx")
    public ResponseResult login(@RequestBody(required = true) WxUserInfo wxUserInfo) {
        log.info("begin to login wxUserInfo: {}" + wxUserInfo.toString());
        try {
            Map<String, String> params = new HashMap<String, String>(4);
            params.put("secret", wxConfig.getAppSecret());
            params.put("appid", wxConfig.getAppId());
            params.put("grant_type", "authorization_code");
            params.put("code", wxUserInfo.getCode());
            String result = HttpUtil.get(wxConfig.getOpenid_url(), params);

            JSONObject jsonObject = JSONObject.fromObject(result);
//            String openid = jsonObject != null && jsonObject.get("openid") != null ? jsonObject.get("openid").toString() : "";
            String openid = "zhaomingxingopenid";
            log.info("getOpenId 得到的openid为: {}", openid);

            return loginService.login(openid, wxUserInfo);
        } catch (Exception e) {
            log.error("登录失败!", e);
            return ResponseResult.fail("登录失败");
        }
    }

    /**
     * 获取图片验证码
     * @param request
     * @param response
     */
    @GetMapping("/login/verifyCode")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response) {

        OutputStream os = null;
        try {

            int width = 200;
            int height = 80;

            BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //生成对应宽高的初始图片
            String randomText = VerifyCodeUtil.getCode(width, height, verifyImg);
            //功能是生成验证码字符并加上噪点，干扰线，返回值为验证码字符
            request.getSession().setAttribute("verifyCode", randomText);

            //必须设置响应内容类型为图片，否则前台不识别
            response.setContentType("image/png");
            //获取文件输出流
            os = response.getOutputStream();
            //输出图片流
            ImageIO.write(verifyImg, "png", os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.flush();
                os.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 刷新图片验证码
     * @param request
     * @param response
     */
    @GetMapping("/login/refreshVerifyCode")
    public void refreshVerifyCode(HttpServletRequest request, HttpServletResponse response) {
        this.getVerifyCode(request, response);
    }

    /**
     * 登出
     *
     * @return
     */
    @PostMapping("login-out")
    public void loginOut() {
        loginService.loginOut();
    }
}
